﻿using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEngine;
using UnityEngine.UI;

namespace Assets.Scripts.UI
{
    /// <summary>
    /// Panel的枚举
    /// </summary>
    public enum PanelType
    {
        GetScorePanel,//查询成绩
        ExamPanel,//考试
        ExamRulePanel,//考生守则
        HomeWorkPanel,//课后作业
        LoginPanel,//登入
        MainPanel,//主界面
        PracticeTestPanel,//模拟考试
        StudentInfoPanel,//学生信息
        TipPanel,//提示信息
        WrongQuePanel,//错题本
        ExamReslutPanel,//考试结果  
        LoadingPanel,//加载界面
        CheckScorePanel,//查询分数
        MockExamPanel,//模拟考试的选择界面
        SettingPanel,//设置按钮
        CollectPanel,//收藏夹
        ExerciseDetailPanel,//问题详情界面
        LoadingLoopPanel,
        CheckScoreTipPanel,
        LoginTimeOutPanel,//登入超时的界面
        AnswerDetailPanel,//答案解析panel
    }

    /// <summary>
    /// Item的枚举
    /// </summary>
    public enum ItemType
    {
        CPExpItem,//课堂表现
        GradeExpItem,//分数
        PictureItem,//用户图片
        RelativeItem,//亲属Item
        RemarkItem,//班主任评分
        StudyExpItem,//学习经历
        TextItem,//文本
        QueItem,//问题
        QueImageItem,//图片问题
        QueVideoItem,//视频问题
        QueAudioItem,//声音问题 
        PaperGuideItem,//试卷导航
        PaperItem,//试卷
        AnsTextItem,//答案
        AnsImageItem,//图片答案
        AnsSubItem,//主观题答案
        HWCourseItem,//作业课程
        HWUnFinishItem,//作业未完成
        HWFinishItem,//作业完成
        CourseItem,//课程的item
        ExerciseItem,//题目
        EmptyItem,//空Item(试卷界面使用)
        TitleItem       
    }

    /// <summary>
    /// UI类型的枚举
    /// </summary>
    public enum UIType
    {
        Null,
        Panel,
        Item,
        Button,
        Text,
    }

    /// <summary>
    /// 功能：UI框架基类
    /// 作者：陈林
    /// 修改时间：2017/9/30
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class UIBase<T> : MonoBehaviour where T : UIBase<T>
    {
        //UIPrefab资源的路径
        private readonly string panelPath = "Prefab/UI/Panel";
        private readonly string itemPath = "Prefab/UI/Item";

        protected abstract UIType UIType { get; }
        protected Transform CreatePanel(PanelType panelType)
        {
            Transform UIParent = GameObject.FindWithTag("UIParent").transform;
            foreach(Transform child in UIParent)
            {
                if (child.name.Equals(panelType + "(Clone)"))
                {
                    child.SetAsLastSibling();
                    return child;
                }
            }
            GameObject go;
            go = Resources.Load<GameObject>(panelPath + "/" + panelType);
            if (go != null)
            {
                go.SetActive(true);
                Transform tsf = Instantiate(go,UIParent).transform;                   
                return tsf;
            }
            else
            {
                Debug.LogWarning("找不到加载的路径："+panelPath+"/"+panelType);
                return null;
            }
        }

        protected Transform CreateItem(ItemType itemType)
        {
            GameObject go;
            go = Resources.Load<GameObject>(itemPath + "/" + itemType);
            if (go != null)
            {
                go.SetActive(true);
                Transform tsf = Instantiate(go).transform;
                return tsf;
            }
            else
            {
                Debug.LogWarning("找不到加载的路径：" + itemType + "/" + itemType);
                return null;
            }
        }

        /// <summary>
        /// 退出UI
        /// </summary>
        protected void Exit()
        {
            if (gameObject != null)
            {
                Destroy(gameObject);
            }               
        }

        /// <summary>
        /// 退出UI
        /// </summary>
        /// <param name="name"></param> 
        protected void Exit(string name)
        {
            Transform tsf = UIManager._Instance.UIParent.Find(name);
            if (tsf != null)
            {
                Destroy(tsf.gameObject);
            }
        }

        /// <summary>
        /// 退出UI
        /// </summary>
        /// <param name="num"></param>
        protected void Exit(int num)
        {
            for (int i = 0; i < num; i++)
            {
                int index = UIManager._Instance.UIParent.childCount - i - 1;
                if (index >= 0)
                {
                    Destroy(UIManager._Instance.UIParent.GetChild(index).gameObject);
                }               
            }
        }

        /// <summary>
        /// 退出所有的UI
        /// </summary>
        protected void AllExit()
        {
            foreach (Transform tsf  in UIManager._Instance.UIParent)
            {
                Destroy(tsf.gameObject);
            }
        }

        protected void ShowText(Text text, string msg)
        {
            text.gameObject.SetActive(true);
            text.text = msg;
        }

        protected void BehindText(Text text)
        {
            text.gameObject.SetActive(false);
        }

        protected void CleanTransformChildren(Transform transform)
        {
            if (transform != null)
            {
                foreach (Transform child in transform)
                {
                    if (child != null)
                        Destroy(child.gameObject);
                }
            }            
        }

        /// <summary>
        /// 将rectTsf归0
        /// </summary>
        /// <param name="tsf"></param>
        protected void SetRectTransformInfo(Transform tsf)
        {
            RectTransform rectTsf = tsf.GetComponent<RectTransform>();
            rectTsf.localScale=Vector3.one;
            rectTsf.offsetMax = Vector2.one;
            rectTsf.offsetMin = Vector2.zero;
            rectTsf.anchoredPosition = Vector2.zero;
            rectTsf.anchorMax = Vector2.one;
            rectTsf.anchorMin = Vector2.zero;
        }


        #region 自动匹配组件

        private void FindComponets(Transform transform, List<FieldInfo> infos)
        {
            foreach (Transform child in transform)
            {
                for (var i = 0; i < infos.Count; i++)
                {
                    var fieldName = infos[i].ToString().Split(' ')[1];
                    if (child.name == fieldName)
                    {
                        string[] names = infos[i].FieldType.ToString().Split('.');
                        string typeName = names[names.Length - 1];
                        infos[i].SetValue(this, child.GetComponent(typeName));
                        infos.Remove(infos[i]);
                    }
                }
                if (child.childCount > 0)
                {
                    FindComponets(child, infos);
                }
            }
        }

        /// <summary>
        /// 自动查找组件优化
        /// </summary>
        protected void AutoFindComponent(Transform tsf, bool isPublic = false)
        {
            var type = GetType();
            List<FieldInfo> infos;
            if (isPublic)
            {
                infos = type.GetFields().ToList(); //找到类中的所有的公共字段
            }
            else
            {
                infos = type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic).ToList(); //找到类中的所有的私有字段
            }
            FindComponets(tsf, infos);
            for (int i = 0; i < infos.Count; i++)
            {
                if (infos[i].GetValue(this) == null)
                {
                    Debug.Log(string.Format("{0},{1},没有找到目标组件", this, infos[i].ToString().Split(' ')[1]));
                }
            }
        }

        #endregion

        #region 初始化信息

        protected virtual void InitOnStart()
        {
        }

        protected virtual void InitOnEnable()
        {
        }

        protected virtual void InitOnAwake()
        {
        }

        protected virtual void InitOnDisable()
        {
        }

        protected virtual void InitOnDestroy()
        {
        }

        //protected abstract void Initialization(params object[] args);

        #endregion

        #region UnityEvent

        //Unity事件

        private void Awake()
        {
            InitOnAwake();   
        }

        private void OnEnable()
        {
            InitOnEnable();
        }

        private void Start()
        {
            InitOnStart();
            switch (UIType)
            {
                case UIType.Panel:
                    transform.SetParent(UIManager._Instance.UIParent);
                    SetRectTransformInfo(transform);                    
                    break;
                default:
                    //todo nothing
                    break;
            }
        }


        private void OnDisable()
        {
            InitOnDisable();
        }

        private void OnDestroy()
        {
            InitOnDestroy();
        }

        protected virtual void Update()
        {

        }

        #endregion
    }
}